from typing import Optional

from django.core.handlers.wsgi import WSGIRequest
from django.contrib.auth import authenticate, login
from django.shortcuts import redirect, render
from django.http import HttpResponse

from . import forms
from . import models


class UsersUtils:

    def authorize_user(self, request: WSGIRequest) -> HttpResponse:
        """ Авторизируем пользователя """

        def login_to_user_account(
            request: WSGIRequest,
            user: Optional[models.CustomUser]
        ) -> HttpResponse:
            """ Входим в аккаунт пользователя """

            if user is not None:
                login(request, user)
                return redirect('scraper_bitrix:home')
            else:
                list_of_errors = [
                    'Проверьте корректность введнного логина или пароля'
                ]
                context = {
                    'form': form,
                    'list_of_errors': list_of_errors
                }
                return render(request, 'registration/login.html', context)


        # ВЫШЕ ОПРЕДЕЛЕНИЕ ФУНКЦИЙ

        form = forms.UserLoginForm(request.POST)

        if form.is_valid():
            cleaned_data = form.cleaned_data
            user = authenticate(
                request=request,
                email=cleaned_data['email'],
                password=cleaned_data['password']
            )
            return login_to_user_account(request, user)
        else:
            return render(request, 'registration/login.html', {'form': form})